﻿namespace Typps
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Web.Script.Serialization;
    using System.Web.UI.WebControls;

    /// <summary>
    /// This converter knows how to serialize following types :
    /// List<CallbackHandler>
    /// The main reason for this converter is also to follow a pascal casing convention
    /// when serializing the types. Unfortunately, there is no better way to map objects using the
    /// builtin JavaScriptSerializer. On the bright side, this is not so bad, also because it does not
    /// make use of reflection, we get a negligable performance boost.
    /// NOTE: currently deserialization is not supported via this converter since it's not required.
    /// </summary>
    public class EventsJavaScriptConverter : JavaScriptConverter
    {
        #region Properties

        public override IEnumerable<Type> SupportedTypes
        {
            //Define the ListItemCollection as a supported type.
            get
            {
                return new ReadOnlyCollection<Type>(new List<Type>(
                 new Type[] {
                    typeof(List<CallbackHandler>)
                 }));
            }
        }

        #endregion Properties

        #region Methods

        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (dictionary == null)
                throw new ArgumentNullException("dictionary");
            //Does not support deserializing. In effect we don't need to deserialize. YAGNI principle?
            return null;
        }

        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            List<CallbackHandler> handlerList = obj as List<CallbackHandler>;
            Dictionary<string, object> result = null;
            ArrayList itemsList = null;
            if (handlerList != null)
            {
                result = new Dictionary<string, object>();
                itemsList = new ArrayList();
                foreach (CallbackHandler cbh in handlerList)
                {
                    Dictionary<string, object> itemsDict = new Dictionary<string, object>();
                    itemsDict.Add("commandName", cbh.CommandName);
                    itemsDict.Add("commandArgument", cbh.CommandArgument);
                    itemsDict.Add("message", cbh.Message);
                    itemsList.Add(itemsDict);
                }
                result["items"] = itemsList;
                return result;
            }
            return new Dictionary<string, object>();
        }

        #endregion Methods
    }
}